import { Rules } from "async-validator";
import { Context, Next } from "koa";
import validate from "../utils/validator";
import { access, sql } from "../logger";
import { callbackData } from "../utils/data.handler";
import menuService from "../service/menu.service";

//字段校验
export const menuValidator = async(ctx:Context,next:Next)=>{
    const rules:Rules = {
        parent_id:{
            type:'number',
            required:true,
            message:'上级菜单不能为空'
        },
        name:{
            type:'string',
            required:true,
            message:'菜单名称不能为空'
        },
        path:{
            type:'string',
            required:true,
            message:'菜单路由不能为空'
        },
        type:{
            type:'string',
            required:true,
            message:'菜单类型不能为空'
        }
    }

    const {error} = await validate<any>(ctx,rules);
    if(error){
        access.info('菜单信息校验错误',{msg:error})
        console.error('菜单信息校验错误',{msg:error})
        ctx.app.emit('error',callbackData('1',error),ctx);
        return false;
    }
    await next();
}
//查重
export const verifyMenu = async(ctx:Context,next:Next)=>{
    const {name,path} = ctx.request.body || {};
    try{
        let res = await menuService.findInfo({name,path});
        if(res){
            sql.error('菜单已存在',{name})
            console.error('菜单已存在',{name})
            ctx.app.emit('error',callbackData('2','菜单已存在'),ctx);
            return false;
        }
    }catch(err){
        sql.error('查询菜单发生错误',err)
        console.error('查询菜单发生错误',err)
        ctx.app.emit('error',callbackData('2','菜单信息错误'),ctx);
        return false;
    }
    await next();
}